package org.duoyi.striver.proxy;

import cn.hutool.core.util.ClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 代理工程
 */
public class ProxyFactory {

    private static final Logger log = LoggerFactory.getLogger(ProxyFactory.class);

    private static final ConcurrentHashMap<Class<Annotation>, Class<InvocationHandler>> proxyMap = new ConcurrentHashMap<>();

    static {
        String annotationPackage = "org.duoyi.striver.proxy.annotation";
        String handlerPackage = "org.duoyi.striver.proxy.handler";

        Set<Class<?>> annotations = ClassUtil.scanPackage(annotationPackage);
        Set<Class<?>> handlers = ClassUtil.scanPackage(handlerPackage);

        Map<String, ? extends Class<?>> handlersMap = handlers.stream().collect(Collectors.toMap(Class::getSimpleName, handler -> handler));
        for (Class<?> annotation : annotations) {
            String annotationName = annotation.getSimpleName();
            Class<?> handler = handlersMap.get(annotationName + "Handler");
            if (handler != null) {
                log.debug("加载代理：{} <-> {}", annotation.getSimpleName(), handler.getSimpleName());
                proxyMap.put((Class<Annotation>) annotation, (Class<InvocationHandler>) handler);
            }
        }
    }

    public static <T> T proxy(T obj) {
        Object result = obj;
        Enumeration<Class<Annotation>> keys = proxyMap.keys();
        Method[] methods = obj.getClass().getDeclaredMethods();
        while (keys.hasMoreElements()) {
            Class<Annotation> annotationClass = keys.nextElement();
            for (Method method : methods) {
                if (method.getDeclaredAnnotation(annotationClass) != null) {
                    Class<InvocationHandler> handlerClass = proxyMap.get(annotationClass);
                    log.debug("动态代理实例: {} -> {}", handlerClass.getSimpleName(), obj.getClass().getSimpleName());
                    Constructor<InvocationHandler> constructor = null;
                    InvocationHandler invocationHandler = null;
                    try {
                        constructor = handlerClass.getConstructor(Object.class);
                        invocationHandler = constructor.newInstance(obj);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException("代理时获取有参构造失败");
                    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        throw new RuntimeException("代理失败");
                    }
                    result = Proxy.newProxyInstance(handlerClass.getClassLoader(), obj.getClass().getInterfaces(), invocationHandler);
                    break;
                }
            }
        }
        return (T) result;
    }

}
